<template name="validation">
	<view class="padding flex flex-direction container">
		<view class="text-center">您本次请求的验证码为</view>
		<view class="text-center code-c">
			<view v-for="item in vCode" class="codeitem">
				{{ item }}
			</view>
		</view>
		<button class="cu-btn round text-white bg-blue align-center" style="margin-bottom: 20rpx;" @click="copyVCode">复制验证码</button>
		<button class="cu-btn round bg-white" style="margin-bottom: 100rpx;color: #007AFF;" @click="refreshVCode">刷新验证码</button>
		<view class="text-center" style="margin-bottom: 40rpx;">验证码过期时间</view>
		<view class="text-center">{{expirationTimeStr}}</view>
		<view class="text-center text-gray" style="position: fixed; bottom: 30rpx;">本服务由微粒阁博客提供技术支持</view>
	</view>
</template>

<script>
	import TOTP from '@/utils/totp.min.js'
	export default {
		data() {
			return {
				key: '',
				vCode: '------',
				expirationTime: null,
				expirationTimeStr: '0000-00-00 00:00:00'
			}
		},
		methods: {
			refreshVCode() {
				if (!this.key || this.key.length != 52) {
					uni.showToast({
						title: 'Key无效'
					});
					return false
				}
				//有效期
				let ex = 30 * 1;
				//有效期为空 或者有效期小于当前时间 更新验证码
				if (!this.expirationTime || Number(this.expirationTime) < Date.now()) {
					const totp = new TOTP(this.key);
					this.vCode = totp.genOTP(ex, 0)
					if (this.expirationTime) {
						uni.showToast({
							title: '验证码已刷新'
						});
					}
					this.expirationTime = new Date(Date.now() + ex * 1000);
					this.expirationTimeStr = this.expirationTime.format("yyyy-MM-dd hh:mm:ss")
				} else {
					uni.showToast({
						title: '验证码扔有效',
						icon: 'error'
					});
				}
			},
			copyVCode() {
				let text = this.vCode
				uni.setClipboardData({
					data: text
				});
			}

		},
		onLoad(obj) {
			this.key = obj.key
			this.refreshVCode()
		}
	}
</script>

<style scoped>
	.container {
		display: flex;
		justify-content: center;
		padding: 60rpx 150rpx 0;
	}
	.code-c {
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-flow: row nowrap;
		margin: 40rpx 0;
	}
	.code-c .codeitem {
		line-height: 1;
		width: 65rpx;
		height: 65rpx;
		line-height: 65rpx;
		border: 2rpx solid #808080;
		border-radius: 20%;
	}
	.cell-bottom {
		margin-bottom: 40rpx;
	}
</style>
